<template>
  <div>
    <div class="nav">
      <router-link to="/dashboard/dash" class="nav-link"><span>首页</span></router-link>
      <router-link :to="{ 
        name: 'Dashboard',
        params: { 
          standardName: standardName 
        }
      }" class="nav-link">
        <span>/</span><span>{{ standardName }}</span>
      </router-link>
      <router-link :to="{ 
        name: 'project-manage',
        params: { 
          param: projectId
        }
      }" class="nav-link">
        <span>/</span><span>{{ projectName }}</span>
      </router-link>
      <router-link :to="{ 
        name: 'people',
        params: { 
          param: projectId,
          standardName: standardName,
          projectName: projectName
        }
      }" class="nav-link">
        <span>/</span><span>人员管理</span>
      </router-link>
      <span>/</span><span class="current-page">培训管理</span>
    </div>

    <div class="training-management">
      <div class="upper-section">
        <!-- 培训资料区域 -->
        <div class="video-section">
          <h2 class="video-section-header">培训资料</h2>
          <div class="media-container">
            <!-- 展示视频列表 -->
            <div
              v-for="(video, index) in trainingVideos"
              :key="video.pgId"
              class="media-item"
            >
              <video :src="video.pgUrl" width="200" height="200" controls>
                您的浏览器不支持视频标签。
              </video>
              <button @click="deleteVideo(index)" class="delete-button">
                删除
              </button>
            </div>
            <!-- 展示试卷列表 -->
            <div
              v-for="(pdf, index) in assessmentPapers"
              :key="pdf.pgId"
              class="media-item"
            >
              <iframe :src="pdf.pgUrl" width="200" height="200"></iframe>
              <button @click="deletePDF(index)" class="delete-button">
                删除
              </button>
            </div>
          </div>
        </div>

        <!-- 上传新视频 -->
        <div class="upload-section">
          <h2 class="centered-header">上传新视频</h2>
          <form class="upload-form" @submit.prevent="uploadVideo">
            <input
              type="file"
              name="video"
              accept="video/*"
              class="file-input"
              @change="handleVideoUpload"
            />
            <button type="submit" class="upload-button">上传</button>
          </form>
        </div>

        <!-- 上传试卷 -->
        <div class="upload-section">
          <h2 class="centered-header">上传试卷</h2>
          <form class="upload-form" @submit.prevent="uploadPDF">
            <input
              type="file"
              name="examPaper"
              accept="application/pdf"
              class="file-input"
              @change="handlePDFUpload"
            />
            <button type="submit" class="upload-button">上传</button>
          </form>
        </div>
      </div>

      <!-- 下半部分：培训证书记录 -->
      <div class="lower-section">
        <div class="certificate-record-section">
          <h2 class="centered-header">培训证书记录</h2>
          <div class="search-and-export">
            <!-- 搜索框 -->
            <input
              type="text"
              v-model="searchQuery"
              placeholder="搜索姓名或证书编号"
            />
            <!-- 搜索按钮 -->
            <button @click="searchRecords">搜索</button>
            <!-- 导出按钮 -->
            <button @click="exportToExcel">导出为Excel</button>
          </div>
          <table>
            <thead>
              <tr>
                <th>姓名</th>
                <th>证书编号</th>
                <th>培训日期</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="record in filteredCertificateRecords" :key="record.id">
                <td>{{ record.name }}</td>
                <td>{{ record.certificateNumber }}</td>
                <td>{{ record.trainingDate }}</td>
              </tr>
            </tbody>
          </table>
          <!-- 分页控制 -->
          <div class="pagination">
            <button @click="prevPage" :disabled="currentPage === 1">
              上一页
            </button>
            <span>第 {{ currentPage }} 页</span>
            <button @click="nextPage" :disabled="currentPage === maxPage">
              下一页
            </button>
            <input
              type="number"
              v-model.number="jumpPage"
              placeholder="跳转到页码"
            />
            <button @click="goToPage(jumpPage)">跳转</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  props: ['projectId'],
  data() {
    return {
      projectId: null,
      standardName: '',
      projectName: '',
      searchQuery: "",
      certificateRecords: [],
      trainingVideos: [],
      assessmentPapers: [],
      currentPage: 1,
      pageSize: 10,
      jumpPage: 1,
      uploadVideoFile: null,
      uploadPdfFile: null,
      loading: false,
      errorMessage: "",
    };
  },
  created() {
    this.fetchTrainingDetails();
    const { param, projectName, standardName, staId } = this.$route.params;
    
    if (param && projectName && standardName) {
      localStorage.setItem('trainParams', JSON.stringify({
        projectId: param,
        projectName,
        standardName,
        staId
      }));
    }
    
    if (!param || !projectName || !standardName) {
      const savedParams = JSON.parse(localStorage.getItem('trainParams') || '{}');
      this.projectId = savedParams.projectId;
      this.projectName = savedParams.projectName || '未知项目';
      this.standardName = savedParams.standardName || '未知标准';
      this.staId = savedParams.staId;
    } else {
      this.projectId = param;
      this.projectName = projectName;
      this.standardName = standardName;
      this.staId = staId;
    }
    
  },
  computed: {
    filteredCertificateRecords() {
      // 先过滤出符合搜索条件的记录
      const filteredRecords = this.certificateRecords.filter(
        (record) =>
          record.name.includes(this.searchQuery) ||
          record.certificateNumber.includes(this.searchQuery)
      );
      // 分页显示
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return filteredRecords.slice(start, end);
    },
    maxPage() {
      // 确保 `maxPage` 是基于过滤后的记录数计算的
      return Math.ceil(
        this.certificateRecords.filter(
          (record) =>
            record.name.includes(this.searchQuery) ||
            record.certificateNumber.includes(this.searchQuery)
        ).length / this.pageSize
      );
    },
  },
  methods: {
    // 获取培训详情，包括视频、试卷和证书记录
    fetchTrainingDetails() {
      if (!this.$route.params.projectId) {
        console.error('项目ID为空');
        return;
      }

      this.loading = true;
      axios
        .get(`http://localhost:8081/training/getTrainingDetails`, {
          params: { projectId: this.$route.params.projectId },
        })
        .then((response) => {
          console.log('完���响应数据:', response.data);
          
          // 打印每个数据的详细信息
          console.log('trainingVideos:', response.data.trainingVideos);
          console.log('assessmentPapers:', response.data.assessmentPapers);
          console.log('trainingRecords:', response.data.trainingRecords);

          // 确保数据存在且为数组
          const trainingVideos = Array.isArray(response.data.trainingVideos) 
            ? response.data.trainingVideos 
            : [];
          const assessmentPapers = Array.isArray(response.data.assessmentPapers) 
            ? response.data.assessmentPapers 
            : [];
          const trainingRecords = Array.isArray(response.data.trainingRecords) 
            ? response.data.trainingRecords 
            : [];

          // 设置数据
          this.trainingVideos = trainingVideos;
          this.assessmentPapers = assessmentPapers;
          
          // 处理培训记录
          this.certificateRecords = trainingRecords.map((record) => ({
            id: record.peId || Math.random(),
            name: record.uName || '未知',
            certificateNumber: record.peId 
              ? `C${record.peId.toString().padStart(3, "0")}` 
              : '未知编号',
            trainingDate: record.pmcTime || '未知日期'
          }));

          console.log('处理后的certificateRecords:', this.certificateRecords);
        })
        .catch((error) => {
          console.error('获取培训详情失败:', error);
          
          // 如果是网络错误，打印更多详细信息
          if (error.response) {
            // 请求已发出，但服务器响应的状态码不在 2xx 范围内
            console.error('错误响应数据:', error.response.data);
            console.error('错误状态码:', error.response.status);
            console.error('错误头:', error.response.headers);
          } else if (error.request) {
            // 请求已发出，但没有收到响应
            console.error('错误请求:', error.request);
          } else {
            // 发送请求时出了些问题
            console.error('错误信息:', error.message);
          }

          this.$message.error("无法获取培训详情，请检查网络连接");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 处理视频文件上传
    handleVideoUpload(event) {
      this.uploadVideoFile = event.target.files[0];
    },

    // 处理PDF文件上传
    handlePDFUpload(event) {
      this.uploadPdfFile = event.target.files[0];
    },

    // 上传视频
    uploadVideo() {
      if (!this.uploadVideoFile) {
        alert("请先选择一个视频文件");
        return;
      }
      console.log('当前上传使用的 projectId:', this.$route.params.projectId);
      let formData = new FormData();
      formData.append("file", this.uploadVideoFile);
      formData.append("projectId", this.$route.params.projectId);
      formData.append("pgName", "培训视频");
      axios
        .post("http://localhost:8081/training/uploadTrainingVideo", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          alert("视频上传成功");
          this.uploadVideoFile = null;
          this.fetchTrainingDetails();
        })
        .catch((error) => {
          console.error("视频上传失败:", error);
          alert("视频上传失败，请重试");
        });
    },

    // 上传PDF试卷
    uploadPDF() {
      if (!this.uploadPdfFile) {
        alert("请先选择试卷文件");
        return;
      }
      let formData = new FormData();
      formData.append("file", this.uploadPdfFile);
      formData.append("projectId", this.$route.params.projectId);
      formData.append("pgName", "试卷");
      axios
        .post("http://localhost:8081/training/uploadTrainingImage", formData, {
          // 确保后端接口正确
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          alert("试卷上传成功");
          this.uploadPdfFile = null;
          this.fetchTrainingDetails();
        })
        .catch((error) => {
          console.error("试卷上传失败:", error);
          alert("试卷上传失败，请重试");
        });
    },

    // 删除视频
    deleteVideo(index) {
      const video = this.trainingVideos[index];
      if (confirm("确定要删除这个视频吗？")) {
        axios
          .delete("http://localhost:8081/training/deleteTrainingVideo", {
            params: { programId: video.pgId }, // 使用 params 传递 programId
          })
          .then(() => {
            this.trainingVideos.splice(index, 1);
            alert("视频删除成功");
          })
          .catch((error) => {
            console.error("视频删除失败:", error);
            alert("视频删除失败，请重试");
          });
      }
    },

    // 删除PDF试卷
    deletePDF(index) {
      const pdf = this.assessmentPapers[index];
      // 可选：在删除前确认或通过API删除
      if (confirm("确定要删除这个试卷吗？")) {
        axios
          .delete("http://localhost:8081/training/deleteExam", {
            params: { programId: pdf.pgId }, // 使用 params 传递 programId
          })
          .then(() => {
            this.assessmentPapers.splice(index, 1);
            alert("试卷删除成功");
          })
          .catch((error) => {
            console.error("试卷删除失败:", error);
            alert("试卷删除失败，请重试");
          });
      }
    },

    // 搜索证书记录
    searchRecords() {
      this.currentPage = 1; // 重置到第一页
    },

    // 导出证书记录为Excel
    exportToExcel() {
      // 实现导出逻辑（示例使用SheetJS库）
      // 需要先安装SheetJS: npm install xlsx
      import("xlsx")
        .then((XLSX) => {
          const data = this.filteredCertificateRecords.map((record) => ({
            姓名: record.name,
            证书编号: record.certificateNumber,
            培训日期: record.trainingDate,
          }));
          const worksheet = XLSX.utils.json_to_sheet(data);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "证书记录");
          XLSX.writeFile(workbook, "培训证书记录.xlsx");
        })
        .catch((error) => {
          console.error("导出失败:", error);
          alert("导出失败，请重试");
        });
    },

    // 编辑证书记录
    editRecord(record) {
      // 实���编辑记录的逻辑，例如打开一个编辑对话框
      alert(`编辑记录: ${record.name}`);
      // 你可以使用模态框或路由导航到编辑页面
    },

    // 删除证书记录
    deleteRecord(record) {
      if (confirm("确定要删除这个证书记录吗？")) {
        axios
          .delete(
            `http://localhost:8081/training/deleteCertificate/${record.id}`
          )
          .then(() => {
            const index = this.certificateRecords.indexOf(record);
            if (index !== -1) {
              this.certificateRecords.splice(index, 1);
              alert("证书记录删除成功");
            }
          })
          .catch((error) => {
            console.error("删除证书记录失败:", error);
            alert("删除证书记录失败，请重试");
          });
      }
    },

    // 分页上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    // 分页下一页
    nextPage() {
      if (this.currentPage < this.maxPage) {
        this.currentPage++;
      }
    },

    // 跳转到指定页码
    goToPage(page) {
      if (page >= 1 && page <= this.maxPage) {
        this.currentPage = page;
      } else {
        alert("无效的页码");
      }
    },

    // 返回方法
    handleBack() {
      this.$router.push({
        name: 'people',
        params: { 
          param: this.$route.params.projectId,
          standardName: this.standardName,
          projectName: this.projectName
        }
      });
    },
  },
};
</script>

<style scoped>
.nav {
  padding: 20px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-link {
  text-decoration: none;
  color: #909399;  /* 非当前页面使用灰色 */
  font-size: 16px;
  transition: color 0.3s;  /* 添加颜色过渡效果 */
}

.nav-link:hover {
  color: #409EFF;  /* 鼠标悬停时变为蓝色 */
}

.nav span {
  color: #909399;  /* 分隔符使用灰色 */
  font-size: 16px;
  margin: 0 5px;
}

.current-page {
  color: #409EFF !important;  /* 当前页面使用蓝色 */
  font-weight: 500;  /* 当前页面加粗 */
}

.nav-back {
  position: absolute;
  right: 20px;
}

.nav-back .el-button {
  font-size: 14px;
  color: #909399;  /* 返回按钮使用灰色 */
}

.nav-back i {
  margin-right: 5px;
}

.training-management {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.video-section-header {
  text-align: center;
  margin-bottom: 20px;
  font-size: 1.5em;
  color: #333;
}

.centered-header {
  text-align: center;
  margin-bottom: 10px;
  font-size: 1.2em;
  color: #555;
}

.upper-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  width: 100%;
}

.lower-section {
  width: 100%;
}

.media-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.media-item {
  position: relative;
  display: inline-block;
}

.delete-button {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  padding: 2px 5px;
}

.delete-button:hover {
  background-color: #ff7875;
}

.video-section {
  flex: 2;
  margin-right: 20px;
}

.upload-section {
  flex: 1;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 300px;
  text-align: center;
}

.upload-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.file-input {
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 100%;
}

.upload-button {
  padding: 5px 15px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: 100%;
}

.upload-button:hover {
  background-color: #66b1ff;
}

.certificate-record-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
}

button {
  cursor: pointer;
  padding: 5px 10px;
  margin-right: 5px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
}

button:hover {
  background-color: #66b1ff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.search-and-export {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.search-and-export input[type="text"] {
  margin-right: 10px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-and-export button {
  margin-left: 10px;
}

.pagination input,
.pagination button {
  margin: 0 5px;
}
</style>
